package com.example.broadcastreceivertest;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class NotificationSender extends Service implements Callback {

    private static final String TAG = "BroadcastRedmiNote";

    public static void startServiceExplicitly(Context context) {
        Intent intent = new Intent(context, NotificationSender.class);
        context.startService(intent);
    }

    public static void startServiceImplicitly(Context context) {
        Intent intent = new Intent("action.pushservice.start");
        context.startService(intent);
    }

    public static PendingIntent getPendingIntentExplicitly(Context context) {
        Intent intent = new Intent(context, NotificationSender.class);
        return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public static PendingIntent getPendingIntentImplicitly(Context context) {
        Intent intent = new Intent("action.pushservice.start");
        return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private Handler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(getMainLooper(), this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final String msg = ":pushservice sendBroadcast delay 10s";
        Log.d(TAG, msg);
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        mHandler.sendEmptyMessageDelayed(0, 10 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean handleMessage(Message msg) {
        final String msg2 = ":pushservice sendBroadcast now";
        Toast.makeText(this, msg2, Toast.LENGTH_SHORT).show();
        Log.d(TAG, "sendBroadcast now");
        sendBroadcastExplicitly();
        return true;
    }

    private void sendBroadcastExplicitly() {
        Intent broadcast = new Intent(NotificationReceiver.ACTION);
        broadcast.setClass(this, NotificationReceiver.class);
        broadcast.setPackage(getPackageName());
        sendBroadcast(broadcast);
    }

    private void sendBroadcastImplicitly() {
        Intent broadcast = new Intent(NotificationReceiver.ACTION);
        broadcast.setClass(this, NotificationReceiver.class);
        sendBroadcast(broadcast);
    }
}

